<template>
  <div class="user-address-add">
    <AddressEdit
      :area-list="areaList"
      show-postal
      show-set-default
      :show-delete="this.$route.query.id?true:false"
      @save="onSave"
      @delete="onDelete"
      :detail-rows="2"
      :address-info="addressInfo"
    ></AddressEdit>
  </div>
</template>

<script>
import { AddressEdit, Toast } from 'vant'
import areaList from '@/api/area'
import { mapActions, mapState } from 'vuex'
export default {
  name: 'UserAddressAdd',
  components: { AddressEdit },
  data () {
    return {
      areaList,
      addressInfo: {
        id: '',
        name: '',
        tel: '',
        address: '',
        province: '',
        city: '',
        county: '',
        areaCode: '',
        addressDetail: '',
        postalCode: ''
      }
    }
  },
  computed: {
    ...mapState(['addressList'])
  },
  created () {
    document.title = this.$route.query.id ? '编辑地址' : '添加地址'
    window.FlutterWebTitle && window.FlutterWebTitle.postMessage(document.title)
    if (this.$route.query.id) {
      const info = this.addressList.find(item => item.id === this.$route.query.id) || {}
      this.addressInfo = { ...info }
    }
  },
  methods: {
    ...mapActions(['addAddress', 'editAddress', 'delAddress']),
    async onSave (content) {
      await Toast.loading({
        message: '正在保存',
        forbidClick: true
      })
      if (content.province === content.city) {
        content.address = content.province + content.county + content.addressDetail
      } else {
        content.address = content.province + content.city + content.county + content.addressDetail
      }
      if (this.$route.query.id) {
        await this.editAddress(content)
      } else {
        content.id = Date.now() + ''
        await this.addAddress(content)
      }
      await Toast.success(this.$route.query.id ? '编辑成功' : '添加成功')
      window.setTimeout(() => {
        Toast.clear()
        this.$router.replace('/user/address')
      }, 500)
    },
    async onDelete (content) {
      await Toast.loading({
        message: '正在删除',
        forbidClick: true
      })
      await this.delAddress(content)
      await Toast.success('删除成功')
      window.setTimeout(() => {
        Toast.clear()
        this.$router.replace('/user/address')
      }, 500)
    }
  }
}
</script>

<style scoped lang='less'>
.van-address-edit {
  padding: 0;
  ::v-deep .van-address-edit__buttons .van-button--danger {
    background-color: #27ba9b;
    border-color: #27ba9b;
  }
  ::v-deep .van-field__label{
    flex: none;
    -webkit-box-flex: none;
    -webkit-flex: none;
    flex: none;
    width: 58px;
  }
}
::v-deep .van-switch--on {
  background-color: #27ba9b;
}
</style>
